/**============================================================================
 Confidential Information - Limited distribution to authorized persons only.
 This software is protected as an unpublished work under the U.S. Copyright
 Act of 1976.

 Copyright (c) 2011, BluePhoenix Solutions, Inc. All rights reserved.
 ----------------------------------------------------------------------------
 file......: TagsPanel.java
 Author....: Vyacheslav Kovalyov
 Created...: 28.10.11

 Description:

 ============================================================================*/
package ru.monyag.pred.swing.ui.tagsCloud;

import org.springframework.util.CollectionUtils;
import ru.monyag.pred.core.tag.Tag;
import ru.monyag.pred.core.tag.TagsCloud;
import ru.monyag.pred.swing.ui.BasePanel;
import ru.monyag.pred.swing.ui.listeners.IUpdateListener;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import static java.lang.Math.ceil;
import static java.lang.Math.log;
import static ru.monyag.pred.core.utils.PredCoreUtils.getString;
import static ru.monyag.pred.swing.util.PredSwingConstants.SELECTED_TAG_COLOR;
import static ru.monyag.pred.swing.util.PredSwingConstants.TAG_COLOR;

/**
 * @author Vyacheslav Kovalyov
 * @version 1.0
 */
public class TagsPanel extends BasePanel {

    public TagsPanel(TagsCloud cloud, IUpdateListener<Tag> listener) {
        super(new FlowLayout());

        this.listener = listener;
        this.cloud = cloud;

        if (CollectionUtils.isEmpty(cloud.getCloud())) {

            add(new JLabel(getString("tags.cloud.not.found")));
        } else {

            for (Tag tag : cloud.getCloud()) {
                initLabel(tag);
            }
        }
    }

    private void initLabel(final Tag tag) {

        final JLabel label = new JLabel(tag.getText());
        setForeground(label, true);

        Font font = label.getFont().deriveFont(getFontSize(tag));
        label.setFont(font);

        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                listener.dispatchUpdate(tag);
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                setForeground(label, false);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                setForeground(label, true);
            }
        });

        add(label);
    }

    private void setForeground(JLabel l, boolean defaultColor) {
        if (defaultColor) {
            l.setForeground(TAG_COLOR);
        } else {
            l.setForeground(SELECTED_TAG_COLOR);
        }
    }

    private float getFontSize(Tag tag) {
        return (float) (10 * (ceil(log(tag.getCount())) + 1));
    }

    private TagsCloud cloud;
    private final IUpdateListener<Tag> listener;
}
